<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */


namespace app\api\controller\android\v10;


use app\api\model\VisaForm;
use App\Http\Middleware\VerifyCsrfToken;
use think\Controller;
use app\api\model\Authority;
use think\db;

use  app\api\model\OrderModel;

class ReserveWage extends Controller
{
    protected $model;
    protected $us;

    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }


    /*
     * 列表项目利润
     */
    public function allProfit()
    {

        $param = Authority::param(['startTime', 'userId', 'type']);
        $arr   = date_parse_from_format('Y年m月', $param['startTime']);
        $time  = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);
        $start = strtotime(date('Y-m-01 00:00:00', $time));//获取指定月份的第一天
        $end   = strtotime(date('Y-m-t 23:59:59', $time)); //获取指定月份的最后一天

        if ($param['type'] == 1 && $param['userId'] != 0) {

            $chanel       = db('user')->where(['status' => 0, 'reserve' => 2, 'user_id' => $param['userId']])->field('username,induction_time,user_id')->find();
            $orderDataSum = 0;

            if ($chanel['induction_time'] != 0) {
                $orderData = $this->ReserveManager($chanel['induction_time'], $start, $end, 1, $chanel['user_id'], $chanel['username']);
            } else {
                $orderData = [
                    'CommissionAmount' => 0,
                    'ProjectProfit' => 0,
                    'base' => 0,
                    'baseFormula' => 0,
                    'aBonus' => 0,
                    'agencyMoney' => 0,
                    'username' => $chanel['username'],
                    'userId' => $chanel['user_id'],
                ];
            }
            $orderDataSum += $orderData['CommissionAmount'];
            $orderList[]  = [
                'username' => $orderData['username'],
                'userId' => $chanel['user_id'],
                'CommissionAmount' => $orderData['CommissionAmount'],
                'formula' => '项目利润*基数*分红比例+代购利润*10%',
            ];

            r_date(['total' => $orderDataSum, 'data' => $orderList], 200);
        }
        if ($param['userId'] == 0 && $param['type'] == 1) {

            $chanel       = db('user')->where(['status' => 0, 'reserve' => 2, 'store_id' => $this->us['store_id']])->field('username,induction_time,user_id')->select();
            $orderDataSum = 0;

            foreach ($chanel as $k => $l) {
                if ($l['induction_time'] != 0) {
                    $orderData = $this->ReserveManager($l['induction_time'], $start, $end, 1, $l['user_id'], $l['username']);
                } else {
                    $orderData = [
                        'CommissionAmount' => 0,
                        'ProjectProfit' => 0,
                        'base' => 0,
                        'baseFormula' => 0,
                        'aBonus' => 0,
                        'agencyMoney' => 0,
                        'username' => $l['username'],
                        'userId' => $l['user_id'],
                    ];
                }
                $orderDataSum += $orderData['CommissionAmount'];

                $orderList[] = [
                    'username' => $orderData['username'],
                    'userId' => $l['user_id'],
                    'CommissionAmount' => $orderData['CommissionAmount'],
                    'formula' => '项目利润*基数*分红比例+代购利润*10%',
                ];
            }
            r_date(['total' => $orderDataSum, 'data' => $orderList], 200);
        }
    }

    /*
    * 单个项目利润详情
    */
    public function singleProfit()
    {
        $param = Authority::param(['startTime', 'userId']);
        $arr   = date_parse_from_format('Y年m月', $param['startTime']);

        $time = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);

        $start = strtotime(date('Y-m-01 00:00:00', $time));//获取指定月份的第一天
        $end   = strtotime(date('Y-m-t 23:59:59', $time)); //获取指定月份的最后一天

        $chanel = db('user')->where(['status' => 0, 'reserve' => 2, 'user_id' => $param['userId']])->field('username,induction_time')->find();

        if ($chanel['induction_time'] != 0) {
            $orderList = $this->ReserveManager($chanel['induction_time'], $start, $end, 1, $param['userId']);
        } else {
            $orderList = [
                'CommissionAmount' => 0,
                'ProjectProfit' => 0,
                'ProjectProfitList' => [
                    'MainMaterialMoney' => 0,
                    'orderForRealityArtificial' => 0,
                    'materialUsage' => 0,
                    'reimbursement' => 0,
                    'money' => 0,
                ],
                'base' => 0,
                'baseNumber' => 0,
                'baseFormula' => 0,
                'aBonus' => 0,
                'conversion' => 0,
                'agencyMoney' => 0,
                'agencyMoneyProfit' => 0
            ];
        }
        r_date(['CommissionAmount' => $orderList['CommissionAmount'], 'CommissionAmountFormula' => '项目利润*基数*分红比例+代购合同分红', 'ProjectProfit' => $orderList['ProjectProfit'], 'ProjectProfitList' => ['MainMaterialMoney' => $orderList['ProjectProfitList']['MainMaterialMoney'],
            'orderForRealityArtificial' => $orderList['ProjectProfitList']['orderForRealityArtificial'],
            'materialUsage' => $orderList['ProjectProfitList']['materialUsage'],
            'reimbursement' => $orderList['ProjectProfitList']['reimbursement'],
            'money' => $orderList['ProjectProfitList']['money']], 'ProjectProfitFormula' => '完工完款金额-人工费-材料费-报销-订单费=项目利润', 'base' => $orderList['base'] * 100, 'baseNumber' => $orderList['baseNumber'] * 100, 'profitCalculation' => '整月项目利润率45%以上,正常基数; 45%以下每低1%,分红基数降低10%;   36以下为0', 'baseFormula' => '项目利润(不扣减订单费)/完工完款金额', 'aBonus' => $orderList['aBonus'] * 100, 'conversion' => $orderList['conversion'] * 100, 'dividendAlgorithm' => '分红比例20%=复购转介绍率大于等于35%;分红比例15%=复购转介绍率小于35%', 'aBonusFormula' => '签约的复购转介绍订单数/当月签单数', 'agencyMoney' => $orderList['agencyMoney'], 'agencyMoneyProfit' => $orderList['agencyMoneyProfit'], 'agencyMoneyFormula' => '按照代购合同所有利润的10%分红', 'username' => $chanel['username']], 200);
    }


    /*
     * 分红比例
     */
    public static function aBonus($induction_time, $userId, $start, $end, $type)
    {
        $order = db('order')->join('contract', 'contract.orders_id=order.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left');

        if ($type == 1) {
            $order->where('order.assignor', $userId);
        } else {
            $order->where('user.store_id', $userId);
        }
        if ($induction_time > $start) {
            $start = $induction_time;
        }
        $order          = $order->whereBetween('contract.con_time', [$start, $end])->field('order.channel_id,order.state')->select();
        $SignedQuantity = [];
        $ActivityOrder  = [];
        foreach ($order as $item) {
            if ($item['state'] > 3) {
                $SignedQuantity[] = $item;
            }
            if ($item['channel_id'] == 27 || $item['channel_id'] == 28) {
                $ActivityOrder[] = $item;
            }
        }
        if (count($SignedQuantity) > 0) {
            $aBonus = count($ActivityOrder) / count($SignedQuantity);
        } else {
            $aBonus = 0;
        }

        if (1638288000 <= $start && $end <= 1646063999) {

            $conversion = 0.2;
        } else {
            if ($aBonus >= 0.35) {
                $conversion = 0.2;
            } else {
                $conversion = 0.15;
            }
        }


        return ['conversion' => sprintf('%.4f', $conversion), 'aBonus' => round($aBonus, 4)];
    }

    /*
     * 储备店长总数据
     */
    public function ReserveManager($induction_time, $start, $end, $type, $id, $username = '')
    {

        $order = \db('order')->field('reimbursement,settlementReimbursement,material_usage,order.order_id,order.cleared_time,order.settlement_time,order.notcost_time,capitalPersonal,contract.con_time')
            ->join('user', 'user.user_id=order.assignor', 'left')
            ->join('contract', 'contract.orders_id=order.order_id', 'left')
            ->join([\db('reimbursement')->field('sum(reimbursement.money)as reimbursement,reimbursement.order_id')->where(['reimbursement.classification' => ['<>', 4], 'reimbursement.status' => 1])->group('reimbursement.order_id')->buildSql() => 'reimbursement'], 'reimbursement.order_id=order.order_id', 'left')
            ->join([\db('reimbursement')->field('sum(reimbursement.money)as settlementReimbursement,reimbursement.order_id')->where(['reimbursement.classification' => 4, 'reimbursement.status' => 1])->group('reimbursement.order_id')->buildSql() => 'reimbursementSettlement'], 'reimbursementSettlement.order_id=order.order_id', 'left')
            ->join([Db::connect(config('database.db2'))->table(config('database.db2')['database'] . '.app_user_order_capital')->field('sum(' . config('database.db2')['database'] . '.app_user_order_capital.personal_price) as capitalPersonal,' . config('database.db2')['database'] . '.app_user_order_capital.order_id')->whereNull('app_user_order_capital.deleted_at')->group(config('database.db2')['database'] . '.app_user_order_capital.order_id')->buildSql() => 'capital'], 'capital.order_id=order.order_id', 'left')
            ->join([\db('material_usage')->field('sum(material_usage.total_price)as material_usage,material_usage.order_id')
                ->where(['material_usage.status' => 1])->group('material_usage.order_id')->buildSql() => 'u'], 'u.order_id=order.order_id', 'left');

        if ($type == 1) {
            $order->where('user.user_id', $id);
        } elseif ($type == 2) {
            $order->where('user.store_id', $id);
        }
        if ($induction_time > $start) {
            $start = $induction_time;
        }


        $orderList = $order->where(function ($quer) use ($start, $end) {
            $quer->whereBetween('order.cleared_time', [$start, $end])->whereOr('order.settlement_time', 'between', [$start, $end]);
        })->where('contract.con_time','>',$induction_time)->group('order.order_id')->select();

        $clearedOrder    = [];
        $settlementOrder = [];

        foreach ($orderList as $item) {
            if (!empty($item['cleared_time']) && ($start <= $item['cleared_time'] && $end >= $item['cleared_time'])) {
                $clearedOrder[] = $item;
            }
            if (!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time'])) {
                $settlementOrder[] = $item;
            }
        }

        $OrderFee = [];
        foreach ($clearedOrder as $value) {
            if ($value['notcost_time'] == 'null' || $value['notcost_time'] == 0) {
                $OrderFee[] = $value;
            }
        }

        $order_id           = array_column($clearedOrder, 'order_id');
        $settlementOrder_id = array_column($settlementOrder, 'order_id');
        // 完款金额
        $EndOfPayment           = (new OrderModel())->TotalProfit($order_id);
        $settlementEndOfPayment = (new OrderModel())->TotalProfit($settlementOrder_id);

        //订单费
        $money = sprintf('%.2f', count($OrderFee) * 120);
        //材料报销
        $material_usage = sprintf('%.2f', array_sum(array_column($clearedOrder, 'material_usage')));
        //报销费用
        $reimbursement           = sprintf('%.2f', array_sum(array_column($clearedOrder, 'reimbursement')));
        $settlementReimbursement = sprintf('%.2f', array_sum(array_column($settlementOrder, 'settlementReimbursement')));

        //人工费
        $order_for_reality_artificial = sprintf('%.2f', array_sum(array_column($clearedOrder, 'capitalPersonal')));
        //项目利润
        $totalMoney = $EndOfPayment['MainMaterialMoney'] - $order_for_reality_artificial - $material_usage - $reimbursement - $money;

        //项目基数
        if (!empty($EndOfPayment['MainMaterialMoney'])) {
            $base = sprintf('%.4f', ($EndOfPayment['MainMaterialMoney'] - $order_for_reality_artificial - $material_usage - $reimbursement) / $EndOfPayment['MainMaterialMoney']);
        } else {
            $base = 0;
        }
        if (1625068800 > $start) {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.44 && $base < 0.45) {
                //B级
                $baseNumber = 0.9;
            } elseif ($base >= 0.43 && $base < 0.44) {
                //C级
                $baseNumber = 0.8;
            } elseif ($base >= 0.42 && $base < 0.43) {
                //C级
                $baseNumber = 0.7;
            } elseif ($base >= 0.41 && $base < 0.42) {
                //C级
                $baseNumber = 0.6;
            } elseif ($base >= 0.40 && $base < 0.41) {
                //C级
                $baseNumber = 0.5;
            } elseif ($base >= 0.39 && $base < 0.40) {
                //C级
                $baseNumber = 0.4;
            } elseif ($base >= 0.38 && $base < 0.39) {
                //C级
                $baseNumber = 0.3;
            } elseif ($base >= 0.37 && $base < 0.38) {
                //C级
                $baseNumber = 0.2;
            } elseif ($base >= 0.36 && $base < 0.37) {
                //C级
                $baseNumber = 0.1;
            } else {
                //D级
                $baseNumber = 0;
            }
        } else {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.40 && $base < 0.45) {
                //B级
                $baseNumber = 0.8;
            } elseif ($base >= 0.35 && $base < 0.40) {
                //C级
                $baseNumber = 0.5;
            } else {
                //D级
                $baseNumber = 0;
            }
        }

        //分红比例
        $aBonus = self::aBonus($induction_time, $id, $start, $end, 1);

        return (['CommissionAmount' => sprintf('%.2f', $totalMoney * $baseNumber * $aBonus['conversion'] + ($settlementEndOfPayment['agencyMoney'] - $settlementReimbursement) * 0.1), 'ProjectProfitList' => [
            'MainMaterialMoney' => $EndOfPayment['MainMaterialMoney'],
            'orderForRealityArtificial' => $order_for_reality_artificial,
            'materialUsage' => $material_usage,
            'reimbursement' => $reimbursement,
            'money' => $money,
        ], 'ProjectProfit' => sprintf('%.4f', $totalMoney), 'base' => $baseNumber, 'baseNumber' => $base, 'aBonus' => $aBonus['conversion'], 'conversion' => $aBonus['aBonus'], 'agencyMoney' => sprintf('%.2f', ($settlementEndOfPayment['agencyMoney'] - $settlementReimbursement) * 0.1), 'agencyMoneyProfit' => $settlementEndOfPayment['agencyMoney'] - $settlementReimbursement, 'username' => $username]);
    }


}